package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.LocationUtils;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**
 * 地区选择
 * @author Administrator
 *
 */
public class HospitalDq extends Activity
{
	private ImageButton ks_preview = null;
	private ListView lv = null;
	private ListView provincelv = null;

	private CustomProgressDialog proDialog;// 加载框
	private HospitalDq oThis = this;

	private Intent mIntent = null;
	private Map<String, Object> map_dq; // 地区map
	List<Map<String, Object>> list_dq = new ArrayList<Map<String, Object>>();// 地区list
	List<Map<String, Object>> list_dqson = new ArrayList<Map<String, Object>>();// 地区list
	MyApplication myApp;

	private int preID = -1;
	private MyAdapter myAdapter;
	private MysonAdapter mysonAdapter;
	private String pid; 
	private String cityname="";
	private int dwflag=0;
	
	private LocationClient mLocationClient = null;
    private BDLocationListener myListener = new MyLocationListener();

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.hostital_dq);
		myApp = (MyApplication) getApplication();
		myApp.addActivity(this);
		// 确定view
		findView();
		//百度sdk定位
		mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
        mLocationClient.registerLocationListener(myListener); // 注册监听函数
        setLocationOption();

		//百度sdk定位
		mLocationClient.start();// 开始定位
		// 初始化界面数据
		GetData();

		// 点击事件
		setOnClick();
	}

	private void GetData()
	{
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();

	}

	class LoadData implements Runnable
	{

		public void run()
		{
			// TODO Auto-generated method stub
			Looper.prepare();
			iniData();
			Looper.loop();
		}
	}

	private void iniData()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("pid", "0"));
			JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOSTMAIN + URLUtils.GETDQLIST, ls);
			JSONArray jsonArr;
			List<Map<String, Object>> tempmain = new ArrayList<Map<String, Object>>();
			if (json != null && !json.equals(""))
			{
				if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
				{
					if (json.getString("dqinfo").length() > 0)
					{
						// 获取地区信息
						jsonArr = new JSONArray(json.getString("dqinfo"));
						JSONObject js = null;
						for (int i = 0; i < jsonArr.length(); i++)
						{
							if(i==0){//添加当前城市
								map_dq = new HashMap<String, Object>();
								map_dq.put("dqdm", "-1");
								map_dq.put("dqmc", "当前城市");
								tempmain.add(map_dq);
							}
							map_dq = new HashMap<String, Object>();
							js = jsonArr.getJSONObject(i);
							// previewId = js.getString("PId");
							map_dq.put("dqdm", js.getString("id"));
							map_dq.put("dqmc", js.getString("dqmc"));
							tempmain.add(map_dq);
						}
						msg.what = 0;
						msg.obj = tempmain;
					}else
					{
						msg.what = -1;
						msg.obj = "暂无数据";
					}
				}
				else
				{
					msg.what = -1;
					msg.obj = "系统错误";
				}
		
			}
			else
			{
				msg.what = -1;
				msg.obj = "网络连接错误！";
			}

			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void GetSonData()
	{
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new LoadSonData().start();
		
	}

	class LoadSonData extends Thread
	{
		@Override
		public void run()
		{
			super.run();
			// TODO Auto-generated method stub
			Looper.prepare();
			if(pid.equals("-1")&&dwflag==0){//第一次打开页面时，如果没有定位成功，则进入等待
				int i = 0;
				while(cityname.equals("")){
					i++;
					try {
						sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(i>5){//如果5秒还没有定位成功则，则提示定位失败
						break;
					}
				}
			}
			

			iniSonData();
			Looper.loop();
		}
	}

	private void iniSonData()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
			if(pid.equals("-1")){//当前城市
				if(cityname.equals("")){
					msg.what = -2;
					msg.obj = "网络异常，自动定位失败";
				}else{
					List<NameValuePair> ls = new ArrayList<NameValuePair>();
					ls.add(new BasicNameValuePair("cityname",cityname));
					JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOSTMAIN + URLUtils.GETDQDWLIST, ls);
					JSONArray jsonArr;
					List<Map<String, Object>> tempmain = new ArrayList<Map<String, Object>>();
					if (json != null && !json.equals(""))
					{
						if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
						{
							if (json.getString("dwinfo").length() > 0)//匹配后台设置
							{
								// 获取定位地区信息
								jsonArr = new JSONArray(json.getString("dwinfo"));
								JSONObject js = null;
								for (int i = 0; i < jsonArr.length(); i++)
								{
									map_dq = new HashMap<String, Object>();
									js = jsonArr.getJSONObject(i);
									map_dq.put("dqdm", js.getString("id"));
									map_dq.put("dqmc", js.getString("dqmc"));
									tempmain.add(map_dq);
								}
								msg.what = 1;
								msg.obj = tempmain;
							}else//不匹配，显示定位城市名，id为-1
							{
								map_dq = new HashMap<String, Object>();
								map_dq.put("dqdm", "-1");
								map_dq.put("dqmc", cityname);
								tempmain.add(map_dq);
								msg.what = 1;
								msg.obj = tempmain;
							}
						}
						else
						{
							msg.what = -2;
							msg.obj = "系统错误";
						}
				
					}
					else
					{
						msg.what = -2;
						msg.obj = "网络连接错误！";
					}
				}
				
			}else{
				List<NameValuePair> ls = new ArrayList<NameValuePair>();
				ls.add(new BasicNameValuePair("pid",pid));
				JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOSTMAIN + URLUtils.GETDQLIST, ls);
				JSONArray jsonArr;
				List<Map<String, Object>> tempmain = new ArrayList<Map<String, Object>>();
				if (json != null && !json.equals(""))
				{
					if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
					{
						if (json.getString("dqinfo").length() > 0)
						{
							// 获取地区信息
							jsonArr = new JSONArray(json.getString("dqinfo"));
							JSONObject js = null;
							for (int i = 0; i < jsonArr.length(); i++)
							{
								map_dq = new HashMap<String, Object>();
								js = jsonArr.getJSONObject(i);
								// previewId = js.getString("PId");
								map_dq.put("dqdm", js.getString("id"));
								map_dq.put("dqmc", js.getString("dqmc"));
								tempmain.add(map_dq);
							}
							msg.what = 1;
							msg.obj = tempmain;
						}else
						{
							msg.what = -2;
							msg.obj = "暂无数据";
						}
					}
					else
					{
						msg.what = -2;
						msg.obj = "系统错误";
					}
			
				}
				else
				{
					msg.what = -2;
					msg.obj = "网络连接错误！";
				}
			}
			

			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case -1:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					break;
				case -2://清空子项数据
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					list_dqson = new ArrayList<Map<String, Object>>();
					if (mysonAdapter == null)
					{
						mysonAdapter = new MysonAdapter(oThis);
					}
					mysonAdapter.setList(list_dqson);
					lv.setAdapter(mysonAdapter);
					mysonAdapter.notifyDataSetChanged();
					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					break;
				case 0://省
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					list_dq = (List<Map<String, Object>>) msg.obj;
					if (myAdapter == null)
					{
						myAdapter = new MyAdapter(oThis);
					}
					myAdapter.setList(list_dq);
					provincelv.setAdapter(myAdapter);
					myAdapter.notifyDataSetChanged();
					break;
				case 1://市
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					list_dqson = (List<Map<String, Object>>) msg.obj;
					if (mysonAdapter == null)
					{
						mysonAdapter = new MysonAdapter(oThis);
					}
					mysonAdapter.setList(list_dqson);
					lv.setAdapter(mysonAdapter);
					mysonAdapter.notifyDataSetChanged();
					break;
				default:
					break;
			}
		};
	};

	class MyAdapter extends BaseAdapter
	{
		private List<Map<String, Object>> list;
		private LayoutInflater mLayoutInflater;

		MyAdapter(Context context)
		{
			mLayoutInflater = LayoutInflater.from(context);
		}

		public List<Map<String, Object>> getList()
		{
			return list;
		}

		public void setList(List<Map<String, Object>> list)
		{
			this.list = list;
		}

		@Override
		public int getCount()
		{
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null)
			{
				convertView = mLayoutInflater.inflate(R.layout.hospital_dq_item, null);
				holder = new ViewHolder();
				holder.tv_id = (TextView) convertView.findViewById(R.id.dq_id);
				holder.tv_mc = (TextView) convertView.findViewById(R.id.dq_mc);
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}
			holder.tv_id.setText((CharSequence) list.get(position).get("dqdm"));
			holder.tv_mc.setText((CharSequence) list.get(position).get("dqmc"));
			if(position==0&&selectItem==-1){//第一个默认当前城市选中
			//	cityname = new LocationUtils().getCityName(oThis);//安卓自带定位
				pid=holder.tv_id.getText().toString();
				GetSonData();
			}
			if (position == selectItem) {  
				convertView.setBackgroundColor(getResources().getColor(R.color.white_bg));
            }   
            else {  
            	if(position==0&&selectItem==-1){
    				convertView.setBackgroundColor(getResources().getColor(R.color.white_bg));
            	}else{
            		convertView.setBackgroundColor(getResources().getColor(R.color.backgroundMYD));
            	}
            }  
			return convertView;
		}
		public  void setSelectItem(int selectItem) {  
            this.selectItem = selectItem;  
        }  
        private int  selectItem=-1;  

	}
	
	class MysonAdapter extends BaseAdapter
	{
		private List<Map<String, Object>> list;
		private LayoutInflater mLayoutInflater;

		MysonAdapter(Context context)
		{
			mLayoutInflater = LayoutInflater.from(context);
		}

		public List<Map<String, Object>> getList()
		{
			return list;
		}

		public void setList(List<Map<String, Object>> list)
		{
			this.list = list;
		}

		@Override
		public int getCount()
		{
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null)
			{
				convertView = mLayoutInflater.inflate(R.layout.hospital_dqson_item, null);
				holder = new ViewHolder();
				holder.tv_id = (TextView) convertView.findViewById(R.id.dq_id);
				holder.tv_mc = (TextView) convertView.findViewById(R.id.dq_mc);
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}
			holder.tv_id.setText((CharSequence) list.get(position).get("dqdm"));
			holder.tv_mc.setText((CharSequence) list.get(position).get("dqmc"));
			
			convertView.setBackgroundColor(getResources().getColor(R.color.white_bg));
			
			return convertView;
		}

	}

	public class ViewHolder
	{
		private TextView tv_id;
		private TextView tv_mc;
	}

	private void setOnClick()
	{
		// 设置preview监听
		ks_preview.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub

				Intent intent = getIntent();
				HospitalDq.this.setResult(0, intent);// 跳转回原来的activity
				HospitalDq.this.finish();// 一定要结束当前activity

			}
		});
		
		// 设置省一级点击事件
		provincelv.setOnItemClickListener(new AdapterView.OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				// TODO Auto-generated method stub
				myAdapter.setSelectItem(arg2);  
				dwflag = 1;
				TextView dq_id = (TextView) arg1.findViewById(R.id.dq_id);
				pid = dq_id.getText().toString();
				GetSonData();
				myAdapter.notifyDataSetChanged();  
			}
		});

		// 设置市一级点击事件
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				// TODO Auto-generated method stub
				mysonAdapter.notifyDataSetChanged();
				TextView dq_mc = (TextView) arg1.findViewById(R.id.dq_mc);
				TextView dq_id = (TextView) arg1.findViewById(R.id.dq_id);

				Intent intent = getIntent();
				intent.putExtra("dq_mc", dq_mc.getText().toString());
				intent.putExtra("dq_id", dq_id.getText().toString());
				preID = arg2;
				HospitalDq.this.setResult(0, intent);// 跳转回原来的activity
				HospitalDq.this.finish();// 一定要结束当前activity
			}
		});
	}

	private void findView()
	{
		mIntent = getIntent();
		lv = (ListView) this.findViewById(R.id.dq_list);
		provincelv = (ListView) this.findViewById(R.id.province_list);
		ks_preview = (ImageButton) this.findViewById(R.id.dq_preview);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
		{
			Intent intent = getIntent();
			HospitalDq.this.setResult(0, intent);// 跳转回原来的activity
			HospitalDq.this.finish();// 一定要结束当前activity
			return false;
		}
		return false;
	}

	 @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        mLocationClient.stop();// 停止定位
    }
	 
	 /**
	     * 设置相关参数
	     */
    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
   //     option.setOpenGps(true);
        option.setAddrType("all");// 返回的定位结果包含地址信息
        option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
        option.setPriority(LocationClientOption.NetWorkFirst);	//设置定位优先级
   //     option.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
        option.setProdName("Ecare");	//设置产品线名称。强烈建议您使用自定义的产品线名称，方便我们以后为您提供更高效准确的定位服务。
        option.disableCache(true);// 禁止启用缓存定位
        mLocationClient.setLocOption(option);
    }
 
    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return;
            if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
	        	 
               cityname = location.getCity();
            }
        }

		@Override
		public void onReceivePoi(BDLocation arg0) {
			// TODO Auto-generated method stub
			
		}
 
    }
}
